'use strict';

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const { userId, reason, contentId, adminId } = event;

  if (!userId || !reason) {
    return {
      code: 400,
      msg: '缺少必要参数',
      data: null
    };
  }

  try {
    // 记录警告信息
    const warningCollection = db.collection('user_warnings');
    const warningResult = await warningCollection.add({
      user_id: userId,
      reason: reason,
      content_id: contentId || null,
      admin_id: adminId || 'admin',
      create_time: new Date(),
      status: 'active'
    });

    // 获取用户当前警告次数
    const warningCountResult = await warningCollection.where({
      user_id: userId,
      status: 'active'
    }).count();

    const warningCount = warningCountResult.total;

    // 更新用户警告计数
    const userCollection = db.collection('uni-id-users');
    await userCollection.doc(userId).update({
      warning_count: warningCount,
      last_warning_time: new Date()
    });

    // 如果警告次数过多，可以自动禁用用户
    let autoAction = null;
    if (warningCount >= 3) {
      await userCollection.doc(userId).update({
        status: 'banned',
        ban_reason: `累计警告${warningCount}次，自动禁用`,
        ban_time: new Date()
      });
      autoAction = 'banned';
    }

    // 发送警告通知给用户（这里可以集成推送服务）
    try {
      // 添加系统消息到用户消息箱
      const messageCollection = db.collection('system_messages');
      await messageCollection.add({
        user_id: userId,
        type: 'warning',
        title: '系统警告',
        content: `您因为违规行为收到警告：${reason}。请遵守平台规则，避免再次违规。`,
        create_time: new Date(),
        read: false
      });
    } catch (messageError) {
      console.log('发送警告消息失败:', messageError);
    }

    // 记录管理员操作日志
    const auditLogCollection = db.collection('audit_logs');
    await auditLogCollection.add({
      target_type: 'user',
      target_id: userId,
      action: 'warning',
      reason: reason,
      admin_id: adminId || 'admin',
      content_id: contentId,
      create_time: new Date(),
      extra_info: {
        warning_count: warningCount,
        auto_action: autoAction
      }
    });

    return {
      code: 200,
      msg: '警告发送成功',
      data: {
        warning_id: warningResult.id,
        user_id: userId,
        warning_count: warningCount,
        auto_action: autoAction
      }
    };
  } catch (error) {
    console.error('发送警告失败:', error);
    return {
      code: 500,
      msg: '发送警告失败',
      data: null
    };
  }
};
